package com.atguigu.srb.core.controller.api;


import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.util.Assert;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.service.UserAccountService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author fan
 * @since 2021-11-22
 */
@RestController
@RequestMapping("/api/core/userAccount")
public class ApiUserAccountController {
    @Resource
    private UserAccountService userAccountService;
    @PostMapping("/auth/commitCharge/{chargeAmt}")
    public R commitCharge(@PathVariable BigDecimal chargeAmt,HttpServletRequest request){
        String token = request.getHeader("token");
        Assert.notNull(token, ResponseEnum.LOGIN_AUTH_ERROR);
        String userId = JwtUtils.getUserId(token);
        Assert.notNull(userId,ResponseEnum.LOGIN_AUTH_ERROR);


        String formStr = userAccountService.commitCharge(chargeAmt,userId);
        return R.ok().data("formStr",formStr);
    }
    @PostMapping("/notify")
    public String notify(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> stringObjectMap = RequestHelper.switchMap(parameterMap);
        //幂等性校验
        String transNo = (String) stringObjectMap.get("agentBillNo");
        boolean isSave = userAccountService.isSaveTransFlow(transNo);
        Assert.isTrue(isSave,ResponseEnum.CHARGE_ERROR_DOWN);
        userAccountService.changeNotify(stringObjectMap);
        return "success";
    }
    @GetMapping("/auth/getAccount")
    public R getAccount(HttpServletRequest request){
        String token = request.getHeader("token");
        Assert.notNull(token, ResponseEnum.LOGIN_AUTH_ERROR);
        String userId = JwtUtils.getUserId(token);
        Assert.notNull(userId,ResponseEnum.LOGIN_AUTH_ERROR);
        BigDecimal account = userAccountService.getAccount(userId);
        return R.ok().data("account",account);
    }
}

